import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/beans/sql.dart';
import 'package:flutter_mwm/impl/impl.dart';
import 'package:flutter_mwm/util/util.dart';
import 'package:flutter_mwm/widget/button.dart';
import 'package:flutter_mwm/widget/edit.dart';
import 'package:flutter_mwm/widget/load.dart';
import 'package:flutter_mwm/widget/text.dart';
import 'package:flutter_mwm/widget/widget.dart';

class SettingsHome extends BaseWidget<SettingsHome> {
  @override
  State<StatefulWidget> createState() {
    return _StateSettings();
  }
}

class _StateSettings extends StateBase<SettingsHome>
    implements HttpCallbackImpl {
  Map<String, String> _tempMap = Map();
  var _helper = DatabaseHelper.internal();
  OverlayEntry _entry;

  @override
  Widget build(BuildContext context) {
    return PhotoWallpaper(
      context,
      title: '设 置',
      child: ListView(
        children: <Widget>[
          _buildWidget('接入地址', _actionServer),
          Line(),
          _buildWidget('代码同步', _actionAsync),
          Line(),
          _buildWidget('关 于', _about),
          //测试按钮
          //_buildWidget('测 试', _test),
          //_buildWidget('清理缓存', _clear),
        ],
      ),
    );
  }

  _buildWidget(String key, VoidCallback callback) {
    return TextViewHorizontalDrawable(
      key,
      background: Colors.transparent,
      highlightBackground: Colors.white10,
      padding: EdgeInsets.all(10.0),
      margin: EdgeInsets.symmetric(vertical: 1.0),
      textColor: Colors.white,
      textSize: 18.0,
      textAlign: TextAlign.start,
      onPressed: callback,
    );
  }

  _exit() {
    Navigator.pop(context);
  }

  _actionServer() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => ServerHome()));
  }

  _actionAsync() {
    if (_tempMap.isNotEmpty) {
      showToast('正在同步中...');
      return;
    }
    _async();
  }

  _about() {
    PlatformKit.package().then((value) {
      showToast('V ${value.version}');
    });
  }

  _test() {
    /* _helper.queryListByBean(TranslateBean(Dictionary.HPZL)).then((value) {
      print('queryListByBean->$value');
    });*/
  }

  _clear() {
    _helper.deleteAll().then((result) {
      showToast('清理完成！');
    });
  }

  _async() {
    /*_show();
    Stream.fromIterable(Dictionary.ARRAY).forEach((item) {
      if (_tempMap.containsKey(item))
        _tempMap.update(item, (_) => '');
      else
        _tempMap.putIfAbsent(item, () => '');
      var _http = HttpKit.getInstance();
      _http.callback(this);
      _http.setTag(item);
      _http.execute(method: "getFrmCode", paramBody: {'dmmc': item});
    }).whenComplete(() {
      _tempMap.clear();
      Log.out(DateTime.now().toString(), tag: "complete");
    });*/
  }

  @override
  void onResult(int what, Object tag, String result) {
    Log.out('${tag.toString()}->$result');
    _saveOrUpdate(result);
    _tempMap.remove(tag.toString());
    if (_tempMap.isEmpty) {
      _dismiss();
      showToast('已同步完成！');
    }
  }

  void _saveOrUpdate(String result) async {
    List<TranslateBean> beanList = TranslateBean.json2List(result);
    _helper.insertOrReplaceList(beanList);
  }

  @override
  void onError(int what, Object tag, String e) {
    _dismiss();
    _tempMap.clear();
    showToast('同步失败');
  }

  void _show() {
    if (null != context) {
      _entry = OverlayEntry(
        builder: (_) => ProgressView(
          '正在同步...',
          null,
        ),
      );
      Overlay.of(context).insert(_entry);
    }
  }

  void _dismiss() {
    if (null != _entry) {
      _entry?.remove();
      _entry = null;
    }
  }

  @override
  void dispose() {
    _dismiss();
    _helper.close();
    super.dispose();
  }
}

class ServerHome extends BaseWidget<ServerHome> {
  @override
  State<StatefulWidget> createState() {
    return _StateServer();
  }
}

class _StateServer extends StateBase<ServerHome> {
  var ipController = TextEditingController();
  var portController = TextEditingController();

  @override
  void initState() {
    _getShared();
    super.initState();
  }

  void _getShared() {
    PreferUtil.get(ServerImpl.KEY_IPADD).then((ipAdd) {
      ipController.text =
          TextUtils.isEmpty(ipAdd) ? ServerImpl.DEFAULT_IPADD : ipAdd;
    });
    PreferUtil.get(ServerImpl.KEY_PORT).then((port) {
      portController.text =
          TextUtils.isEmpty(port) ? ServerImpl.DEFAULT_PORT : port;
    });
  }

  @override
  Widget build(BuildContext context) {
    return PhotoWallpaper(context,
        title: '接入地址',
        child: ListView(children: <Widget>[
          Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 10.0),
            padding: EdgeInsets.all(8.0),
            child: Column(
              children: <Widget>[
                EditText(
                  showClearIcon: true,
                  labelText: '服务器地址',
                  controller: ipController,
                  maxLines: 1,
                  keyboardType: TextInputType.emailAddress,
                ),
                Line(),
                EditText(
                  showClearIcon: true,
                  labelText: '服务器端口(0～65536)',
                  controller: portController,
                  maxLines: 1,
                  maxLength: 5,
                  keyboardType: TextInputType.number,
                  inputFormatter: [WhitelistingTextInputFormatter.digitsOnly],
                ),
              ],
            ),
          ),
          Row(children: <Widget>[
            ExpandedButton(
              '提 交',
              background: Color(0xFF3d6488),
              highlightBackground: Color(0xFF3d7999),
              radius: 6.0,
              textColor: Color(0xFF0099CC),
              textSize: 18.0,
              padding: EdgeInsets.all(8.0),
              margin: EdgeInsets.only(
                  top: 15.0, left: 10.0, right: 10.0, bottom: 10.0),
              onPressed: _save,
            )
          ])
        ]));
  }

  _save() {
    String ipAdd = ipController.text;
    if (TextUtils.isEmpty(ipAdd)) {
      showToast("IP地址不能为空");
      return;
    }
    PreferUtil.set(ServerImpl.KEY_IPADD, ipAdd);
    String port = portController.text;
    String baseUrl;
    if (TextUtils.isEmpty(port)) {
      baseUrl = ipAdd;
      PreferUtil.set(ServerImpl.KEY_PORT, '');
    } else {
      if (!ServerImpl.portValid(port)) {
        showToast("端口号填写范围：0～65536");
        return;
      }
      baseUrl = "$ipAdd:$port";
      PreferUtil.set(ServerImpl.KEY_PORT, port);
    }
    PreferUtil.set(ServerImpl.KEY_BASEURL, baseUrl).then((success) {
      Navigator.pop(context);
    });
  }
}
